package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.specialPrice;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CCompanys;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUser;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TSpecialPrice;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TSpecialPriceType;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetAllSpecialPricesVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
public class SpecialPriceBu {
    @Autowired
    private ITSpecialPriceService specialPriceService;
    @Autowired
    private ICProductsInfoService icProductsInfoService;
    @Autowired
    private ICCompanysService icCompanysService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ITSpecialPriceTypeService specialPriceTypeService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;

    //查询定价类型
    public SzResult getAllSpecialPriceType(String typeName, String plantId) {
        QueryWrapper<TSpecialPriceType> queryWrapper = new QueryWrapper<>();
        if (typeName != null) {
            queryWrapper.like(!typeName.equals(""), "PRICE_TYPE_NAME", typeName);
        }
        queryWrapper.orderByAsc("PRICE_SORT");
        queryWrapper.eq("DATA_FROM", plantId);
        List<TSpecialPriceType> specialPriceTypes = specialPriceTypeService.list(queryWrapper);
        return SzResult.success(specialPriceTypes);
    }

    //    修改定价类型的排序
    public SzResult updateSpecialPriceTypeSort(String id, Integer sort, String plantId, String token) throws Exception {
        String userId = StpUtil.getLoginIdByToken(token).toString();
        SysUser user = userInfoDao.getUser(userId);
//        先判断除了自己以外是否有相同排序的类型
        QueryWrapper<TSpecialPriceType> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("ID", id);
        queryWrapper.eq("PRICE_SORT", sort);
        TSpecialPriceType specialPriceType = specialPriceTypeService.getOne(queryWrapper);
        if (specialPriceType != null) {
            return SzResult.Error("该序号已有其他定价类型，请先修改被占用的序号至空闲序号");
        }
        TSpecialPriceType specialPriceType1 = specialPriceTypeService.getById(id);
        specialPriceType1.setPriceSort(sort);
        specialPriceTypeService.updateById(specialPriceType1);
        sysLogBu.logRecord("定价管理", user.getTrueName(), "【修改定价类型的排序】：将【" + specialPriceType1.getPriceTypeName() + "】的执行顺号由" + specialPriceType1.getPriceSort() + "改到了" + sort.toString(), plantId);
        return SzResult.Success();
    }

    //    停用定价类型的使用
    public SzResult updateSpecialPriceTypeEnableFlag(String id, Integer enableFlag, String plantId, String token) throws Exception {
        String userId = StpUtil.getLoginIdByToken(token).toString();
        SysUser user = userInfoDao.getUser(userId);
        TSpecialPriceType specialPriceType = specialPriceTypeService.getById(id);
        specialPriceType.setEnableFlag(enableFlag);
        specialPriceTypeService.updateById(specialPriceType);
        if (enableFlag == 1) {
            sysLogBu.logRecord("定价管理", user.getTrueName(), "【修改定价类型的使用】：启用【" + specialPriceType.getPriceTypeName() + "】", plantId);
        } else {
            sysLogBu.logRecord("定价管理", user.getTrueName(), "【修改定价类型的使用】：停用【" + specialPriceType.getPriceTypeName() + "】", plantId);
        }
        return SzResult.Success();
    }

    //    查询所有定价数据
    public SzResult getAllSpecialPrices(Integer pageNum, Integer pageSize, String startTime, String endTime, String coId, String pdtId, String priceTypeId, Integer executeType, String token, String plantId) {
        Page<TSpecialPrice> page = new Page<>(pageNum, pageSize);
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("DEL_FLAG", 1);
        queryWrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + " END_TIME " + " >= " + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");
        if (coId != null) {
            queryWrapper.eq(!coId.equals(""), "CO_ID", coId);
        }
        if (pdtId != null) {
            queryWrapper.eq(!pdtId.equals(""), "PDT_ID", pdtId);
        }
        if (priceTypeId != null) {
            queryWrapper.eq(!priceTypeId.equals(""), "PRICE_TYPE_ID", priceTypeId);
        }
        queryWrapper.eq(executeType != null, "EXECUTE_TYPE", executeType);
        queryWrapper.orderByDesc("END_TIME");
        queryWrapper.eq("DATA_FROM", plantId);
        IPage<TSpecialPrice> list = specialPriceService.page(page, queryWrapper);
        List<TSpecialPrice> specialPrices = list.getRecords();
        List<GetAllSpecialPricesVo> specialPriceVos = new ArrayList<>();
        for (TSpecialPrice specialPrice : specialPrices) {
            GetAllSpecialPricesVo specialPriceVo = new GetAllSpecialPricesVo();
            specialPriceVo.setId(specialPrice.getId());
            specialPriceVo.setPdtId(specialPrice.getPdtId());
            specialPriceVo.setPdtName(icProductsInfoService.getById(specialPrice.getPdtId()).getPdtinfPdt());
            specialPriceVo.setCoId(specialPrice.getCoId());
            QueryWrapper<CCompanys> cCompanysQueryWrapper = new QueryWrapper<>();
            cCompanysQueryWrapper.eq("ID", specialPrice.getCoId());
            CCompanys cCompanys = icCompanysService.getOne(cCompanysQueryWrapper);
            specialPriceVo.setCoName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
            specialPriceVo.setPriceTypeId(specialPrice.getPriceTypeId());
            specialPriceVo.setPriceType(specialPriceTypeService.getById(specialPrice.getPriceTypeId()).getPriceTypeName());
            specialPriceVo.setExecuteType(specialPrice.getExecuteType());
            specialPriceVo.setStartTime(specialPrice.getStartTime());
            specialPriceVo.setEndTime(specialPrice.getEndTime());
            specialPriceVo.setPrice(specialPrice.getPrice());
            specialPriceVo.setNum(specialPrice.getNum());
            specialPriceVo.setResidueNum(specialPrice.getResidueNum());
            specialPriceVo.setCreateTime(specialPrice.getCreateTime());
            if (specialPrice.getCreaterId() != null) {
                specialPriceVo.setCreaterId(specialPrice.getCreaterId());
                specialPriceVo.setCreaterName(sysUserService.getById(specialPrice.getCreaterId()).getTrueName());
            }
            specialPriceVo.setUpdateTime(specialPrice.getUpdateTime());
            if (specialPriceVo.getUpdatorId() != null) {
                specialPriceVo.setUpdatorId(specialPrice.getUpdatorId());
                specialPriceVo.setUpdatorName(sysUserService.getById(specialPrice.getUpdatorId()).getTrueName());
            }
            specialPriceVo.setDelFlag(specialPrice.getDelFlag());
            specialPriceVo.setPriceDesc(specialPrice.getPriceDesc());
            specialPriceVo.setDataFrom(specialPrice.getDataFrom());
            specialPriceVos.add(specialPriceVo);
        }
        Long total = list.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", specialPriceVos);
        return SzResult.success(map);
    }

    //    新增定价数据
    public SzResult addSpecialPrice(
            String id,
            BigDecimal price,
            String priceTypeId,
            String priceType,
            Integer executeType,
            BigDecimal num,
            String pdtId,
            String coId,
            String startTime,
            String endTime,
            String priceDesc,
            String token,
            String plantId) {
//        先查询下
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDT_ID", pdtId);
        queryWrapper.eq("CO_ID", coId);
        queryWrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + " END_TIME " + " >= " + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" + endTime + "'" + " ) " + " or " +
                " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");
        queryWrapper.eq("PRICE_TYPE_ID", priceTypeId);
        queryWrapper.eq("EXECUTE_TYPE", executeType);
        queryWrapper.eq("DATA_FROM", plantId);
        TSpecialPrice specialPrice1 = specialPriceService.getOne(queryWrapper);
        if (specialPrice1 != null) {
            return SzResult.error("该时间区间已存在相同销售类型的数据");
        }
        TSpecialPrice specialPrice = new TSpecialPrice();
        specialPrice.setId(id);
        specialPrice.setPrice(price);
        specialPrice.setPriceTypeId(priceTypeId);
        specialPrice.setPriceType(priceType);
        specialPrice.setExecuteType(executeType);
        specialPrice.setNum(num);
        specialPrice.setPdtId(pdtId);
        specialPrice.setCoId(coId);
        specialPrice.setStartTime(LocalDateTime.parse(startTime));
        specialPrice.setEndTime(LocalDateTime.parse(endTime));
        specialPrice.setPriceDesc(priceDesc);
        specialPrice.setCreateTime(LocalDateTime.now());
        specialPrice.setDataFrom(plantId);
        String userId = StpUtil.getLoginIdByToken(token).toString();
        specialPrice.setCreaterId(userId);
        boolean tSpecialPrice = specialPriceService.save(specialPrice);
        if (tSpecialPrice) {
            return SzResult.Success();
        } else {
            return SzResult.error("新增数据出错");
        }
    }

    //    修改updateSpecialPrice
    public SzResult updateSpecialPriceDes(
            String id,
            String priceDesc,
            String token,
            String plantId) {
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        TSpecialPrice specialPrice = specialPriceService.getById(id);
        specialPrice.setPriceDesc(priceDesc);
        specialPrice.setUpdateTime(LocalDateTime.now());
        String userId = StpUtil.getLoginIdByToken(token).toString();
        specialPrice.setUpdatorId(userId);
        boolean tSpecialPrice = specialPriceService.updateById(specialPrice);
        if (tSpecialPrice) {
            return SzResult.success("修改成功");
        } else {
            return SzResult.error("修改数据出错");
        }
    }

    //修改数据
    public SzResult updateSpecialPrice(
            String id,
            BigDecimal price,
            String priceTypeId,
//            String priceType,
            Integer executeType,
            BigDecimal num,
            String pdtId,
            String coId,
            String startTime,
            String endTime,
            String priceDesc,
            String token,
            String plantId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义匹配的格式
        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<TSpecialPrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        TSpecialPrice specialPrice = specialPriceService.getOne(queryWrapper);
        // 计算已经消耗的数量
        BigDecimal consumedNum = specialPrice.getNum().subtract(specialPrice.getResidueNum());
        if (!Objects.equals(price, specialPrice.getPrice())) {
//            从什么价格改成另外一个价格
            logMsg.append("价格从【").append(specialPrice.getPrice()).append("】改成【").append(price).append("】");
            specialPrice.setPrice(price);
        }
            specialPrice.setPriceTypeId(priceTypeId);
        QueryWrapper<TSpecialPriceType> tSpecialPriceTypeQueryWrapper = new QueryWrapper<>();
        tSpecialPriceTypeQueryWrapper.eq("ID", priceTypeId);
        TSpecialPriceType tSpecialPriceType = specialPriceTypeService.getOne(tSpecialPriceTypeQueryWrapper);
        if (!Objects.equals(tSpecialPriceType.getPriceTypeName(), specialPrice.getPriceType())) {
//            从��么类型改成��外一个类型
            logMsg.append("定价类型从【").append(specialPrice.getPriceType()).append("】改成【").append(tSpecialPriceType.getPriceTypeName()).append("】");
            specialPrice.setPriceType(tSpecialPriceType.getPriceTypeName());
        }
//        specialPrice.setPriceType(priceType);
        if (!Objects.equals(executeType, specialPrice.getExecuteType())) {
//            从��么执行��号改成��外一个执行��号
            logMsg.append("销售类型从【").append(specialPrice.getExecuteType()).append("】改成【").append(executeType).append("】");
            specialPrice.setExecuteType(executeType);
        }
        if (!Objects.equals(num, specialPrice.getNum())) {
//            从��么数量改成��外一个数量
            logMsg.append("执行量从【").append(specialPrice.getNum()).append("】改成【").append(num).append("】");
            specialPrice.setNum(num);
        }
        if (!Objects.equals(pdtId, specialPrice.getPdtId())) {
//            从���么产品改成��外一个产品
            logMsg.append("品种id从【").append(specialPrice.getPdtId()).append("】改成【").append(pdtId).append("】");
            specialPrice.setPdtId(pdtId);
        }
        if (!Objects.equals(coId, specialPrice.getCoId())) {
//            从��么公司改成��外一个公司
            logMsg.append("公司id从【").append(specialPrice.getCoId()).append("】改成【").append(coId).append("】");
            specialPrice.setCoId(coId);
        }
        if (!Objects.equals(LocalDateTime.parse(startTime,formatter), specialPrice.getStartTime())) {
//            从���么开始时间改成��外一个开始时间
            logMsg.append("开始时间从【").append(specialPrice.getStartTime()).append("】改成【").append(LocalDateTime.parse(startTime,formatter)).append("】");
            specialPrice.setStartTime(LocalDateTime.parse(startTime,formatter));
        }
        if (!Objects.equals(LocalDateTime.parse(endTime,formatter), specialPrice.getEndTime())) {
//            从���么结束时间改成���外一个结束时间
            logMsg.append("结束时间从【").append(specialPrice.getEndTime()).append("】改成【").append(LocalDateTime.parse(endTime,formatter)).append("】");
            specialPrice.setEndTime(LocalDateTime.parse(endTime,formatter));
        }
            specialPrice.setPriceDesc(priceDesc);
        specialPrice.setUpdateTime(LocalDateTime.now());
        specialPrice.setResidueNum(num.subtract(consumedNum));
        String userId = StpUtil.getLoginIdByToken(token).toString();
        SysUser sysUser = sysUserService.getById(userId);
        specialPrice.setUpdatorId(userId);
        boolean tSpecialPrice = specialPriceService.updateById(specialPrice);
//        sysLogBu.logRecord("定价管理", logMsg.toString(), specialPrice.getDataFrom());
        if (tSpecialPrice) {
            sysLogBu.logRecord("定价管理",sysUser.getTrueName(), String.valueOf(logMsg),plantId);
            return SzResult.success("修改成功");
        } else {
            return SzResult.Error("修改数据出错");
        }
    }



}